#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include "linklist.h"
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

list_pnode head = NULL;
int linklist_len = 0;

//消费者线程
void *consumer(void *p)
{
	 list_pnode temp;
	 for (;;) {
		 pthread_mutex_lock(&lock);
		 while (head->next == NULL)
		 	pthread_cond_wait(&has_product, &lock);
		 //移除head->next的第1个节点
		 temp = head->next;
		 printf("Consume started\n");
		 printf("Consume %d \n", temp->data);
		 remove_linklist(head);
		 linklist_len--;
		 show_linklist(head); ////打印链表的节点的内容
		 printf("Consume over len=%d\n", linklist_len);
		 pthread_mutex_unlock(&lock);
		 //sleep(rand() % 1);
		 usleep(100000);
		 
		
	 }
	 return NULL;
}

//生产者线程
void *producer(void *p)
{
	list_pnode new_pnode;
	//初始化单向链表
	init_linklist(&head);	
 	for (;;) {
		new_pnode = (list_pnode)malloc(sizeof(list_node)); //创建链表节点对象
		if (NULL == new_pnode) {
			perror("malloc");
			exit(1);
		}
		new_pnode->data = rand() % 1000 + 1; //产生1000以内的整数, 初始化节点对象数据
		printf("Produce %d\n", new_pnode->data);
		pthread_mutex_lock(&lock);
		//添加到链表 头插
		insert_linklist(head, new_pnode);
		linklist_len++;
		
		show_linklist(head); //打印链表的节点的内容
		printf("Produce over len=%d\n", linklist_len);		
		pthread_mutex_unlock(&lock);
		pthread_cond_signal(&has_product);
		usleep(100000*(rand() % 3));
		
	}
	return NULL;
}
int main(int argc, char *argv[]) 
{
	 pthread_t pid, cid; 
	 srand(time(NULL)); //随机种子 产生随机数的初始化
	 pthread_create(&pid, NULL, producer, NULL);
	 pthread_create(&cid, NULL, consumer, NULL);
	 pthread_join(pid, NULL);
	 pthread_join(cid, NULL);
	 return 0;
}


